package com.dotstone.chipism.view;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.Scene;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import com.dotstone.chipism.listener.onReachTopListener;

public class CicleMenuLayoutBlue extends ViewGroup {
	private int mRadius;
	/**
	 * 该容器内child item的默认尺寸
	 */
	private static final float RADIO_DEFAULT_CHILD_DIMENSION = 1 / 3f;
	/**
	 * 该容器的内边距,无视padding属性，如需边距请用该变量
	 */
	private static final float RADIO_PADDING_LAYOUT = 0;

	/**
	 * 如果移动角度达到该值，则屏蔽点击
	 */
	private static final int NOCLICK_VALUE = 3;

	/**
	 * 该容器的内边距,无视padding属性，如需边距请用该变量
	 */
	private float mPadding;
	/**
	 * 布局时的开始角度
	 */
	private double mStartAngle = -90;
	private double currentStartAngle;
	/**
	 * 菜单项的文本
	 */
	private List<Scene> mScenes = new CopyOnWriteArrayList<Scene>();
	private List<Scene> mShowScenes = new CopyOnWriteArrayList<Scene>();
	private List<Scene> mHideScenes = new CopyOnWriteArrayList<Scene>();
	private String lastBottomScene;
	private String currentBottomScene;
	private int n;
	// private List<Group> mGroups;
	private int head;
	private int tail;
	private boolean clockwise;
	private long lastChange = 0;
	private long currentChange = 0;
	/**
	 * 检测按下到抬起时旋转的角度
	 */
	private float mTmpAngle;
	/**
	 * 检测按下到抬起时使用的时间
	 */
	// private long mDownTime;
	private List<View> views = new ArrayList<View>();
	/**
	 * 判断是否正在自动滚动
	 */
	// private boolean isFling;
	private int centerX;
	private int centerY;
	private int l;
	private float angleDelay;
	private int topPosition;
	private int topId;
	private float angular_velocity;
	// private boolean needToUpdate = false;

	public CicleMenuLayoutBlue(Context context, AttributeSet attrs) {
		super(context, attrs);
		// 无视padding
		setPadding(0, 0, 0, 0);
	}

	/**
	 * 设置布局的宽高，并策略menu item宽高
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int resWidth = 0;
		int resHeight = 0;
		/**
		 * 根据传入的参数，分别获取测量模式和测量值
		 */
		int width = MeasureSpec.getSize(widthMeasureSpec);
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);

		int height = MeasureSpec.getSize(heightMeasureSpec);
		int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		/**
		 * 如果宽或者高的测量模式非精确值
		 */
		if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) {
			// 主要设置为背景图的高度
			resWidth = getSuggestedMinimumWidth();
			// 如果未设置背景图片，则设置为屏幕宽高的默认值
			resWidth = resWidth == 0 ? getDefaultWidth() : resWidth;

			resHeight = getSuggestedMinimumHeight();
			// 如果未设置背景图片，则设置为屏幕宽高的默认值
			resHeight = resHeight == 0 ? getDefaultWidth() : resHeight;
		} else {
			// 如果都设置为精确值，则直接取小值；
			resWidth = resHeight = Math.min(width, height);
		}
		setMeasuredDimension(resWidth, resHeight);
		// 获得半径
		mRadius = Math.max(getMeasuredWidth(), getMeasuredHeight());
		// menu item数量
		final int count = getChildCount();
		// menu item尺寸
		int childSize = (int) (mRadius * RADIO_DEFAULT_CHILD_DIMENSION);
		// menu item测量模式
		int childMode = MeasureSpec.UNSPECIFIED;
		// 迭代测量
		for (int i = 0; i < count; i++) {
			final View child = getChildAt(i);
			// 计算menu item的尺寸；以及和设置好的模式，去对item进行测量
			int makeMeasureSpec = -1;
			makeMeasureSpec = MeasureSpec.makeMeasureSpec(childSize, childMode);
			child.measure(makeMeasureSpec, makeMeasureSpec);
		}
		mPadding = RADIO_PADDING_LAYOUT * mRadius;
	}

	/**
	 * MenuItem的点击事件接口
	 * 
	 * @author zhy
	 * 
	 */
	public interface OnMenuItemClickListener1 {
		void itemClick(String id);
	}

	public interface OnAddSceneListener {
		void addClick();
	}

	/**
	 * view的中间角度为270.0 说明该view处于最顶端 调用接口 让监听该接口的Activity改变外圈数据
	 */

	private onReachTopListener onReachTopListener;

	public void setOnReachTopListener(onReachTopListener onReachTopListener) {
		this.onReachTopListener = onReachTopListener;
	}

	/**
	 * MenuItem的点击事件接口
	 */
	private OnMenuItemClickListener1 mOnMenuItemClickListener;
	private OnAddSceneListener mAddSceneListener;

	/**
	 * 设置MenuItem的点击事件接口
	 * 
	 * @param mOnMenuItemClickListener
	 */
	public void setOnMenuItemClickListener(OnMenuItemClickListener1 mOnMenuItemClickListener) {
		this.mOnMenuItemClickListener = mOnMenuItemClickListener;
	}

	public void setmAddSceneListener(OnAddSceneListener mAddSceneListener) {
		this.mAddSceneListener = mAddSceneListener;
	}

	public void updateChildView(final String id, boolean open) {
		for (int i = 0; i < mShowScenes.size(); i++) {
			if (mShowScenes.get(i).getSceneId().equals(id)) {
//				Log.i("circle", "要更新状态的id是" + id + " " + open + " " + n);
				n = i;
			}
		}
		if (n < views.size()) {
			TextView tv = (TextView) views.get(n).findViewById(R.id.id_circle_menu_item_text);
			if (tv != null) {
				tv.setVisibility(View.VISIBLE);
				if (open) {
					tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
					tv.setTextColor(Color.WHITE);
				} else {
					tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
					tv.setTextColor(Color.parseColor("#9edffe"));
				}
				tv.setText(mShowScenes.get(n).getSceneName());
				//
			}
		}
	}

	/**
	 * 设置menu item的位置
	 */
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		int layoutRadius = mRadius;
		centerX = mRadius / 2;
		centerY = mRadius / 2;

		// Log.i("circle", "blue"+layoutRadius+" "+getWidth()+" "+ );
		final int childCount = getChildCount();
		// Log.i("circle", "242蓝圈中有" + childCount + "个子控件");
		int left, top;
		// menu item 的尺寸
		int cWidth = (int) (layoutRadius * RADIO_DEFAULT_CHILD_DIMENSION);
		// 根据menu item的个数，计算角度
		if (getChildCount() != 0) {
			angleDelay = 360 / getChildCount();
		} else {
			angleDelay = 360;
		}
		// 遍历去设置menuitem的位置
		for (int i = 0; i < childCount; i++) {
			final View child = getChildAt(i);
			mStartAngle %= 360;
			if (mStartAngle < 0) {
				currentStartAngle = 360 + mStartAngle;
			} else {
				currentStartAngle = mStartAngle;
			}
			// Log.i("circle", i + " currentStartAngle = " + currentStartAngle);
			if (currentStartAngle == 270.0) { // 该view为最高点 调用接口
				if (i <= mShowScenes.size() && i != mShowScenes.size()) {
					topPosition = i;
				}
			}
			if (currentStartAngle == 90.0) {
				if (mScenes.size() >= 8 && i != 7) {
//					Log.i("circle", "滑到最底层的item " + i + " " + mShowScenes.get(i).getSceneName());
					if (System.currentTimeMillis() - lastChange > 200) {
						lastChange = System.currentTimeMillis();
						if (clockwise) { // 顺时针
							mHideScenes.add(mShowScenes.get(i));
							// Log.i("circle", "移除" +
							// mShowScenes.get(i).getSceneName());
							mShowScenes.remove(i);
							mShowScenes.add(i, mHideScenes.get(0));
							// Log.i("circle", "添加" +
							// mShowScenes.get(i).getSceneName());
							mHideScenes.remove(0);
						} else { // 逆时针
							mHideScenes.add(0, mShowScenes.get(i));
							// Log.i("circle", "移除" +
							// mShowScenes.get(i).getSceneName());
							mShowScenes.remove(i);
							mShowScenes.add(i, mHideScenes.get(mHideScenes.size() - 1));
							// Log.i("circle", "添加" +
							// mShowScenes.get(i).getSceneName());
							mHideScenes.remove(mHideScenes.size() - 1);
						}
						resetContent(i);
					} else {

					}
				}
			}
			// 计算，中心点到menu item中心的距离
			float tmp = layoutRadius / 2f - cWidth / 2 - mPadding;
			// tmp cosa 即menu item中心点的横坐标
			left = layoutRadius / 2
					+ (int) Math.round(tmp * Math.cos(Math.toRadians(currentStartAngle)) - 1 / 2f * cWidth);
			// tmp sina 即menu item的纵坐标
			top = layoutRadius / 2
					+ (int) Math.round(tmp * Math.sin(Math.toRadians(currentStartAngle)) - 1 / 2f * cWidth);

			child.layout(left, top, left + cWidth, top + cWidth);
			// 叠加尺寸
			mStartAngle += angleDelay;
		}

	}

	public int getTopPosition() {
		return topPosition;
	}

	public String getTopId() {
		if (topPosition != 9 && topPosition < mShowScenes.size()) {
			return mShowScenes.get(topPosition).getSceneId();
		} else {
			return "-1";
		}
	}

	/**
	 * 记录上一次的x，y坐标
	 */
	private float mLastX;
	private float mLastY;
	private long mLastTime;
	private float mLastX1;
	private float mLastY1;
	private long downTime;
	private long upTime;

	/**
	 * 自动滚动的Runnable
	 */
	// private AutoFlingRunnable mFlingRunnable;

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		float x = event.getX();
		float y = event.getY();
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mLastX = x;
			mLastY = y;
			mLastX1 = x;
			mLastY1 = y;
			mTmpAngle = 0;
			l = getL(x, y);
			// needToUpdate = false;
			if (l > mRadius / 2) {
				return false;
			}
			topPosition = 9;
			downTime = System.currentTimeMillis();
			break;
		case MotionEvent.ACTION_MOVE:
			/**
			 * 获得开始的角度
			 */
			float start = getAngle(mLastX, mLastY);
			/**
			 * 获得当前的角度
			 */
			float end = getAngle(x, y);
			// Log.i("circle", "start = "+start+" end = "+end);
			l = getL(x, y);
			if (l > mRadius / 2) {
				return false;
			}
			if (System.currentTimeMillis() - mLastTime > 200) {
				mLastTime = System.currentTimeMillis();
				float start1 = getAngle(mLastX, mLastY);
				float end1 = getAngle(x, y);
				// Log.i("circle", "获取角度差 = " + Math.abs(end1 - start1));
				// if (Math.abs(end1 - start1) < 10) {
				// needToUpdate = true;
				// Log.e("circle", "需要刷新");
				// } else {
				// needToUpdate = false;
				// }
				mLastX1 = x;
				mLastY1 = y;
			}
			if (getQuadrant(x, y) == 1 || getQuadrant(x, y) == 4) {
				mStartAngle += end - start;
				mTmpAngle += end - start;
				// Log.i("circle", "1 4象限");
				if (end < start) {
					clockwise = false;
				} else {
					clockwise = true;
				}
			} else {
				// 二、三象限，色角度值是付值
				mStartAngle += start - end;
				mTmpAngle += start - end;
				if (end < start) {
					clockwise = true;
				} else {
					clockwise = false;
				}
			}
			// 重新布局
			mLastX = x;
			mLastY = y;
			requestLayout();
			// invalidate();
			break;
		case MotionEvent.ACTION_UP:

			// 计算，每秒移动的角度
			// Log.e("circle", "手势上提");
			// 当手势上抬时 停止转盘转动
			// 获取views.get(0)的角度
			// 判断该控件的初始角与45度的余值
			// 让其产生回弹效果 弹回中间位置
			// 判断哪个控件属于最顶端的位置 调用接口
			upTime = System.currentTimeMillis();
			adjustArea();
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (onReachTopListener != null && topPosition <= mShowScenes.size()) {
						onReachTopListener.reach(mShowScenes.get(topPosition).getSceneId());
						resetContent(9);
						Log.i("circle", "手势抬起 = " + mShowScenes.get(topPosition).getSceneId());
					}else{
						onReachTopListener.reach("");
					}
				}
			}, 100);
			l = getL(x, y);
			if (l > mRadius / 2) {
				return false;
			}
			// needToUpdate = false;
			// 如果当前旋转角度超过NOCLICK_VALUE屏蔽点击
			if (Math.abs(mTmpAngle) > NOCLICK_VALUE) {
				// Log.i("circle", "屏蔽点击");
				return true;
			}
			break;
		}
		return super.dispatchTouchEvent(event);
	}

	Handler mHandler = new Handler();

	private void resetContent(int p) {
		if (mShowScenes.size() < 8) {
			for (int i = 0; i < mShowScenes.size(); i++) {
				TextView tv1 = (TextView) views.get((i)).findViewById(R.id.id_circle_menu_item_text);
				tv1.setText(mShowScenes.get(i).getSceneName());
			}
		} else {
			for (int i = 0; i < 7; i++) {
				TextView tv1 = (TextView) views.get((i)).findViewById(R.id.id_circle_menu_item_text);
				tv1.setText(mShowScenes.get(i).getSceneName());
			}
		}
	}

	/**
	 * 主要为了action_down时，返回true
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return true;
	}

	private void adjustArea() {
		double differ = mStartAngle % 45;
		if (differ < 45 / 2) {
			mStartAngle -= differ;
		} else {
			mStartAngle += (45 - differ);
		}
		// requestLayout();
		if (upTime - downTime > 100) {
			requestLayout();
			Log.i("wmy", "需要回弹");
			// invalidate();
		} else {
			Log.i("wmy", "不需要回弹");
		}
	}

	/**
	 * 根据触摸的位置，计算角度
	 * 
	 * @param xTouch
	 * @param yTouch
	 * @return
	 */
	private float getAngle(float xTouch, float yTouch) {
		double x = xTouch - (mRadius / 2d);
		double y = yTouch - (mRadius / 2d);
		return (float) (Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI);
	}

	/**
	 * 根据当前位置计算象限
	 * 
	 * @param x
	 * @param y
	 * @return
	 */
	private int getQuadrant(float x, float y) {
		int tmpX = (int) (x - mRadius / 2);
		int tmpY = (int) (y - mRadius / 2);
		if (tmpX >= 0) {
			return tmpY >= 0 ? 4 : 1;
		} else {
			return tmpY >= 0 ? 3 : 2;
		}
	}

	/**
	 * 设置菜单条目的图标和文本
	 * 
	 * @param resIds
	 */
	public void setScenes(List<Scene> mScenes) {
		this.mScenes = mScenes;
		Log.i("circle", "460 setScenes = " + " " + mScenes.size());
		// 获取了传进来的情景集合
		// 将其对应到每个view上
		setInView();
	}

	private void setInView() {
		Log.i("circle", "467 setInView = " + mScenes.size());
		if (mScenes.size() != 0) {
			if (mScenes.size() < 8) {
				mShowScenes = mScenes;
				for (int i = 0; i < mShowScenes.size(); i++) {
					TextView tv = (TextView) views.get((i)).findViewById(R.id.id_circle_menu_item_text);
					tv.setText(mShowScenes.get(i).getSceneName());
				}
				TextView tv = (TextView) views.get(mShowScenes.size()).findViewById(R.id.id_circle_menu_item_text);
				tv.setText("+");
				for (int i = mShowScenes.size() + 1; i < 8; i++) {
					TextView tv1 = (TextView) views.get((i)).findViewById(R.id.id_circle_menu_item_text);
					tv1.setText("");
				}
				// tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
			} else {
				for (int i = 0; i < 7; i++) {
					TextView tv = (TextView) views.get((i)).findViewById(R.id.id_circle_menu_item_text);
					tv.setText(mScenes.get(i).getSceneName());
					 mShowScenes.add(mScenes.get(i));
				}
//				mShowScenes = mScenes.subList(0, 7);
				TextView tv = (TextView) views.get(7).findViewById(R.id.id_circle_menu_item_text);
				tv.setText("+");
				// tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
				mHideScenes.clear();
				 for (int i = 7; i < mScenes.size(); i++) {
				 mHideScenes.add(mScenes.get(i));
				 }
//				mHideScenes.clear();
//				mHideScenes.addAll(mScenes.subList(7, mScenes.size()));
//				head = 0;
//				tail = 7;
				Log.e("circle", "mHideScenes.size() = " + mHideScenes.size());
			}
		} else {
			Log.i("circle", "第一个控件是加号");
			TextView tv = (TextView) views.get(0).findViewById(R.id.id_circle_menu_item_text);
			tv.setText("+");
			tv.setVisibility(View.VISIBLE);
			for (int i = 1; i < views.size(); i++) {
				TextView tv1 = (TextView) views.get(i).findViewById(R.id.id_circle_menu_item_text);
				tv1.setText("");
				tv1.setVisibility(View.VISIBLE);
			}
		}
	}

	public void addMenus() {
		removeAllViews();
		mHideScenes.clear();
		mShowScenes.clear();
		mScenes.clear();
		mStartAngle = -90;
		LayoutInflater mInflater = LayoutInflater.from(getContext());
		Log.e("circle", "516 addMenus");
		/**
		 * 根据用户设置的参数，初始化view
		 */
		for (int i = 0; i < 8; i++) {
			final int j = i;
			View view = mInflater.inflate(R.layout.circle_menu_item, this, false);
			final TextView tv = (TextView) view.findViewById(R.id.id_circle_menu_item_text);
			tv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					// TODO Auto-generated method stub
					if (mOnMenuItemClickListener != null && mScenes.size() > j) {
						if (j == 7) {

						} else {
							mOnMenuItemClickListener.itemClick(mShowScenes.get(j).getSceneId());
//							Log.i("circle", "570点击了 j = " + mShowScenes.get(j).getSceneId() + " "
//									+ mShowScenes.get(j).getSceneName());
						}
						if (tv.getText().toString().equals("+")) {
							mAddSceneListener.addClick();
						}
					}
					if (tv.getText().toString().equals("+")) {
						// Log.i("circle", "点击了 添加 ");
						mAddSceneListener.addClick();
					}
				}
			});
			view.setTag(i);
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					// TODO Auto-generated method stub
					// Log.i("circle", "view.getTag() = " + view.getTag());
					if (mOnMenuItemClickListener != null && mScenes.size() > j) {
						if (j == 7) {
							mAddSceneListener.addClick();
						} else {
							mOnMenuItemClickListener.itemClick(mShowScenes.get(j).getSceneId());
//							Log.i("circle", "595点击了 j = " + mShowScenes.get(j).getSceneId() + " "
//									+ mShowScenes.get(j).getSceneName());
						}
					}
				}
			});
			addView(view);
			views.add(view);
		}

	}

	/**
	 * 获得默认该layout的尺寸
	 * 
	 * @return
	 */
	private int getDefaultWidth() {
		WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(outMetrics);
		return Math.min(outMetrics.widthPixels, outMetrics.heightPixels);
	}

	private int getL(float x, float y) {
		l = (int) (Math.sqrt(Math.pow(Math.abs(x - centerX), 2) + Math.pow(Math.abs(y - centerY), 2)));
		return l;
	}

}